import fs from 'fs'
import path from 'path'
import fetch from 'node-fetch'
import { XiuXianUtils } from './xiuxian_utils.js'
import { fileURLToPath } from 'url'

export class XiuXianData {
    constructor() {
        this.gameState = {}
        this.sects = {}
        this.config = {}
        this.realms = []
        this.monsters = []
        this.shop = []
        this.tasks = []
        this.skills = []
        this.paths = {}
        this.utils = new XiuXianUtils()
        this.initPaths()
        this.loadDefaultConfigs()
    }

    initPaths() {
        const rootDir = process.cwd()
        const resourcesDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'resources')
        const configDir = path.join(rootDir, 'config')
        this.paths = {
            gameData: path.join(rootDir, 'xiuxian_data.json'),
            config: path.join(configDir, 'xiuxian_config.yaml'),
            realms: path.join(configDir, 'xiuxian_realms.json'),
            monsters: path.join(configDir, 'xiuxian_monsters.json'),
            shop: path.join(configDir, 'xiuxian_shop.json'),
            tasks: path.join(configDir, 'xiuxian_tasks.json'),
            skills: path.join(configDir, 'xiuxian_skills.json'),
            sects: path.join(configDir, 'xiuxian_sects.json'),
            Web: path.join(resourcesDir, 'html', 'xiuxian.html'),
            credentials: path.join(configDir, 'credentials.json')
        }
        
        // 确保config目录存在
        if (!fs.existsSync(configDir)) {
            fs.mkdirSync(configDir, { recursive: true });
        }
    }

    loadDefaultConfigs() {
        const defaultConfigPath = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'default_config');
        this.defaultRealms = JSON.parse(fs.readFileSync(path.join(defaultConfigPath, 'xiuxian_realms.json'), 'utf8'));
        this.defaultMonsters = JSON.parse(fs.readFileSync(path.join(defaultConfigPath, 'xiuxian_monsters.json'), 'utf8'));
        this.defaultShop = JSON.parse(fs.readFileSync(path.join(defaultConfigPath, 'xiuxian_shop.json'), 'utf8'));
        this.defaultTasks = JSON.parse(fs.readFileSync(path.join(defaultConfigPath, 'xiuxian_tasks.json'), 'utf8'));
        this.defaultSkills = JSON.parse(fs.readFileSync(path.join(defaultConfigPath, 'xiuxian_skills.json'), 'utf8'));
    }

    async loadAllData() {
        const defaultConfig = { cd: { 修炼: 5, 探索: 10, 战斗: 15, 宗门修炼: 60 } };
        const defaultCredentials = { userName: 'admin', password: '88888888' };

        this.gameState = this.utils.loadJSON(this.paths.gameData, {});
        this.config = this.utils.loadYAML(this.paths.config, defaultConfig);
        this.credentials = this.loadOrCreateConfig(this.paths.credentials, defaultCredentials);

        this.realms = this.loadOrCreateConfig(this.paths.realms, this.defaultRealms);
        this.monsters = this.loadOrCreateConfig(this.paths.monsters, this.defaultMonsters);
        this.shop = this.loadOrCreateConfig(this.paths.shop, this.defaultShop);
        this.tasks = this.loadOrCreateConfig(this.paths.tasks, this.defaultTasks);
        this.skills = this.loadOrCreateConfig(this.paths.skills, this.defaultSkills);
        this.sects = this.loadOrCreateConfig(this.paths.sects, {});
    }

    loadOrCreateConfig(path, defaultData) {
        if (fs.existsSync(path)) {
            return JSON.parse(fs.readFileSync(path, 'utf8'));
        } else {
            fs.writeFileSync(path, JSON.stringify(defaultData, null, 2), 'utf8');
            console.log(`创建新的配置文件: ${path}`);
            return defaultData;
        }
    }

    saveConfig(configName) {
        const path = this.paths[configName];
        if (path && this[configName]) {
            this.utils.saveJSON(path, this[configName]);
            console.log(`保存 ${configName} 配置到 ${path}`);
        } else {
            console.error(`无法保存 ${configName} 配置`);
        }
    }

    loadAndUpdateJSON(filePath, defaultValue) {
        let data;
        if (fs.existsSync(filePath)) {
            data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
            let updated = false;
            let newItems = [];
            defaultValue.forEach(item => {
                if (typeof item === 'object' && item !== null) {
                    const existingItem = data.find(d =>
                        (d.id && item.id && d.id === item.id) ||
                        (d.name && item.name && d.name === item.name)
                    );
                    if (!existingItem) {
                        data.push(item);
                        newItems.push(item.name || item.id);
                        updated = true;
                    } else {
                        let itemUpdated = false;
                        Object.keys(item).forEach(key => {
                            if (JSON.stringify(existingItem[key]) !== JSON.stringify(item[key])) {
                                existingItem[key] = item[key];
                                itemUpdated = true;
                            }
                        });
                        if (itemUpdated) {
                            newItems.push(`更新: ${item.name || item.id}`);
                            updated = true;
                        }
                    }
                } else if (!data.includes(item)) {
                    data.push(item);
                    newItems.push(item);
                    updated = true;
                }
            });
            if (updated) {
                this.utils.saveJSON(filePath, data);
                console.log(`更新 ${filePath}`);
                console.log(`添加或更新了: ${newItems.join(', ')}`);
            }
        } else {
            data = defaultValue;
            this.utils.saveJSON(filePath, data);
            console.log(`创建 ${filePath}`);
            console.log(`添加了 ${defaultValue.length} 个默认项`);
        }
        return data;
    }
}
